import axios from "axios";

/**
 * class合并
 * ```ts
 * clsx('abc', { def: true }) => 'abc def'
 * ```
 * @param names
 */
export function clsx(
  ...names: (
    | string
    | undefined
    | false
    | { [key: string]: boolean | undefined }
  )[]
) {
  let tmp = names.map((t) => {
    if (typeof t === "object") {
      return Object.keys(t)
        .filter((k) => !!t[k])
        .join(" ");
    }
    return t;
  });
  const temp = tmp.filter((v) => !!v);
  return temp.join(" ");
}

/**
 * 图片文件转base64-url
 * @param file
 */
export const toUrlFromImage = (file: Blob) => {
  return new Promise<string>((resolve, reject) => {
    if (file.type.includes("image")) {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        resolve(reader.result as string);
      };
      reader.onerror = (err) => reject(err);
    }
  });
};

/**
 * 将视频转换成图片url
 * @param file
 * @param type
 */
export const toUrlFromVideo = (
  file: Blob | string,
  type: "data-url" | "object-url" = "object-url"
) => {
  return new Promise<string>((resolve, reject) => {
    const video = document.createElement("video");
    video.setAttribute("crossOrigin", "anonymous");
    video.preload = "auto";

    if (file instanceof Blob) {
      file = URL.createObjectURL(file);
    }
    video.src = file;

    video.onloadeddata = () => {
      const canvas = document.createElement("canvas");
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      const ctx = canvas.getContext("2d")!;
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      if (type === "data-url") {
        resolve(canvas.toDataURL("image/jpeg"));
      } else {
        canvas.toBlob((blob) => {
          resolve(URL.createObjectURL(blob!));
        });
      }
    };
    video.onerror = (err) => reject(err);
  });
};

/**
 * 金额转换
 * @param number
 * @returns ¥123,456.79
 */
export const NumberFormat = (number: number) => {
  const china = new Intl.NumberFormat("zh-CN", {
    style: "currency",
    currency: "CNY",
  });
  return china.format(number);
};

/**
 * 生成随机颜色
 */
export const getRandomColor = (): string => {
  var color = "#" + Math.random().toString(16).substring(2, 8);
  return color.length !== 7 ? getRandomColor() : color;
};

/**
 * 获取当前用户属地
 */
export const getIpCo = async () => {
  const ret = await axios.get("https://api.ipify.org/?format=json");

  if (ret.data.ip) {
    const ret2 = await axios.get(`https://ipapi.co/${ret.data.ip}/json`);
    return ret2.data.city;
  }
};

/**
 * 获取切换到userpage的path
 * @param account
 * @param pathname
 */
export const getToUserPath = (account: string, pathname: string) => {
  const uparams = pathname.match(/^\/u\/(\d{6})(.*)$/) ?? [, , ""];
  return `/u/${account}${uparams[2]}`;
};
